package com.yczy365.petmall.controller;

import com.yczy365.petmall.mapper.UserMapper;
import com.yczy365.petmall.pojo.dto.UserDTO;
import com.yczy365.petmall.pojo.dto.UserRegDTO;
import com.yczy365.petmall.pojo.entity.User;
import com.yczy365.petmall.pojo.vo.AdminVO;
import com.yczy365.petmall.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    private UserMapper mapper;
@RequestMapping("/userLogin")
    public int  userLogin(@RequestBody UserDTO userDTO, HttpSession session, HttpServletResponse response){
    System.out.println(userDTO);
    UserVO userVO = mapper.selectByUsername(userDTO.getUsername());
    System.out.println(userVO);
if (userVO!=null){
    if (userVO.getPassword().equals(userDTO.getPassword())){
        session.setAttribute("user",userVO);
        if (userDTO.getRem()){
            Cookie c1 = new Cookie("username", userVO.getUsername());
            Cookie c2 = new Cookie("password", userVO.getPassword());
            c1.setMaxAge(60*60*24*30);
            response.addCookie(c1);
            response.addCookie(c2);
            session.setAttribute("user",userVO);
        }
        return 1;
    }return 2;

}

return 3;
}
@RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
    UserVO userVO = mapper.selectByUsername(userRegDTO.getUsername());
    if (userVO == null) {
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        mapper.insert(user);
        return 1;
    }
    return 2;
}
    @RequestMapping("/CurrentUser")
    public UserVO adminCurrentAdmin(HttpSession session){
        UserVO admin = (UserVO) session.getAttribute("user");
        return admin;
    }
}
